package com.fjh.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fjh.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Configuration
public class LoginRoute {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder){
        return builder.routes()
                .route("auth-server-router-id",r->r.path("/oauth/token")
                .filters(f->f.modifyResponseBody(String.class,String.class,(exchange,s)->{
                    //拿到响应值
                    JSONObject jsonObject = JSON.parseObject(s);
                    String accessToken = jsonObject.getString("access_token");
                    if (StringUtils.hasText(accessToken)){
                        //有token就存redis
                        Long expiresIn = jsonObject.getLong("expires_in");
                        redisTemplate.opsForValue()
                                .set(GatewayConstant.OAUTH_PREFIX + accessToken, "", Duration.ofSeconds(expiresIn));
                    }
                    return Mono.just(s);
                })).uri("lb://auth-server"))
                        .build();
    }
}

